package com.wl.user.service.impl;

import com.wl.basic.controller.VerifyCodeController;
import com.wl.basic.exception.BusinessException;
import com.wl.basic.util.Md5Utils;
import com.wl.basic.util.StrUtils;
import com.wl.org.domain.Employee;
import com.wl.user.domain.Logininfo;
import com.wl.user.domain.User;
import com.wl.user.dto.EmailDto;
import com.wl.user.dto.UserDto;
import com.wl.user.mapper.LogininfoMapper;
import com.wl.user.mapper.UserMapper;
import com.wl.user.service.IUserService;
import com.wl.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    //注入redis
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired//注入java邮箱对象
    /* private JavaMailSender javaMailSender;*/
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {
        String code = userDto.getPhoneCode();
        String phone = userDto.getPhone();
        String password = userDto.getPwd();
        String passwordRepeat = userDto.getConfirmPwd();
        //空值校验
       if(StringUtils.isEmpty(code) || StringUtils.isEmpty(phone)|| StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
           //抛异常
           throw new BusinessException("数据不能为空");
       }
        //密码校验
        if(!password.equalsIgnoreCase(passwordRepeat)){
            //抛异常
            throw new BusinessException("密码不一致！请重新输入");
        }
        //验证码是否过期
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            //抛异常
            throw new BusinessException("验证码过期");
        }
        if (!obj.toString().split(":")[0].equals(code)){
            //抛异常
            throw new BusinessException("手机验证码错误");
        }
        //保存数据
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo 获取自增id
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }



    /**
     * 邮箱的业务
     * @param emailDto
     */
    @Override
    public void emailRegister(EmailDto emailDto) throws MessagingException {
        //空值判断
        String confirmPwd = emailDto.getConfirmPwd();
        String email = emailDto.getEmail();
        String pwd = emailDto.getPwd();
        //数据为空判断
        if(StringUtils.isEmpty(confirmPwd) || StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd)){
            throw new BusinessException("数据不能为空");
        }
        //密码校验
        if(!pwd.equalsIgnoreCase(confirmPwd)){
            throw new BusinessException("密码错误");
        }
        //校验邮箱
        //3.发送激活邮件
        User user = userMapper.loadEmail(email);
        if (user!=null){
            throw new BusinessException("邮箱已被注册");
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();//获取java邮箱
        //
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        //设置发见人
        mimeMessageHelper.setFrom("2026029753@qq.com");
        //设置接收人
        //动态获取

        mimeMessageHelper.setTo(emailDto.getEmail());
        //S设置主题
        mimeMessageHelper.setSubject("注册激活邮件!!!");
        //设置内容
        mimeMessageHelper.setText("<h1>注册激活邮件成功!!!</h1><h3><a href='http://localhost:8080/shop/active/"+emailDto.getEmail()
                +"'>点击该链接激活</a></h3>",true);
        javaMailSender.send(mimeMessage);

        //保存数据
        //保存数据
        User user1 = emailDto2Email(emailDto);
        Logininfo logininfo = email2Logininfo(user1);
        //1.先添加t_logininfo 获取自增id
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user1.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }
    //自定义的
    private User emailDto2Email(EmailDto emailDto) {
        User user = new User();
        user.setEmail(emailDto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        //密码要加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(emailDto.getPwd() + salt);
        emailDto.setPwd(md5Pwd);
        return user;
    }
    private Logininfo email2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则拷贝属性值
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户
        logininfo.setDisable(true);
        return logininfo;
    }




    /**
     *
     * @param userDto
     * @return
     */
    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //密码要加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    /**
     *
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则拷贝属性值
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void save(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);

        //保存user
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }


    @Override
    @Transactional
    public void remove(Long id) {
        //删除登录信息logininfo
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());

        //删除user信息
        userMapper.remove(id);
    }

    @Override
    @Transactional
    public void update(User user) {//网上传递的user时没有loggininfo_id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);

        //获取登录信息id
        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();

        //创建logininfo
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);//id,type ,state
        //将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo);//5个数据新的 - 用户名，邮箱，电话，盐值，密码
        //重置logininfoId
        logininfo.setId(logininfoId);
        logininfoMapper.update(logininfo);
    }

}
